#include "place_category_view.h"
#include "ui_place_category_view.h"

#include "place_sub_category_view.h"

PlaceCategoryView::PlaceCategoryView(QWidget *parent) :
    ViewBase(parent),
    ui(new Ui::PlaceCategoryView),
    placeSubCategoryView_(0)
{
    ui->setupUi(this);

    QAction *backSoftkeyAction = new QAction(QString("Back"), this);
    backSoftkeyAction->setSoftKeyRole(QAction::NegativeSoftKey);
    QObject::connect(backSoftkeyAction, SIGNAL(triggered()),
                     this, SLOT(hide()));
    addAction(backSoftkeyAction);

    connect(ui->lstPlaceCategories, SIGNAL(itemActivated(QListWidgetItem*)),
            this, SLOT(showPlaceSubCategory(QListWidgetItem*)));
}

PlaceCategoryView::~PlaceCategoryView()
{
    delete ui;
    if (placeSubCategoryView_) {
        delete placeSubCategoryView_;
    }
}


void PlaceCategoryView::IssueRequest() {
  RequestMethod request(this, QString("xml"), QString("Places.getAllCategory"));

  placeCategories.clear();

  ui->lstPlaceCategories->clear();

  if (handler_) {
    handler_->IssueRequest(request);
  }
}

int PlaceCategoryView::ProcessResult(RequestMethod &r, QDomElement &e) {
  int re = parse_result(e);
  if (re == 0) {
    for (int i = 0; i < placeCategories.count(); ++i) {
      cate &c = placeCategories[i];
      ui->lstPlaceCategories->addItem(c.cn_cate);
    }
  }
  return re;
}

int PlaceCategoryView::parse_result(QDomElement &e) {
  QDomNodeList list = e.childNodes();
  for (int i = 0; i < list.count(); ++i) {
    QDomElement n = list.at(i).toElement();
    if (n.nodeName() == QString("cate")) {
      cate c;
      parse_cate(n, c);
      placeCategories.push_back(c);
    }
  }

  return 0;
}

void PlaceCategoryView::showPlaceSubCategory(QListWidgetItem *item) {
    for (int i = 0; i < placeCategories.count(); ++i) {
        cate &c = placeCategories[i];
        if (c.cn_cate == item->text()) {
            if (!placeSubCategoryView_) {
                placeSubCategoryView_ = new PlaceSubCategoryView(this);
                placeSubCategoryView_->SetRequestHandler(handler_);
            }

            placeSubCategoryView_->Show();
            placeSubCategoryView_->setPlaceCategory(c);

            placeSubCategoryView_->IssueRequest();
        }
    }
}
